
package org.summerframework.component.upload.fastdfs;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件上传结果类
 *
 * <ul>
 * <li><code>isSuccess</code> 是否上传成功
 * <li><code>groupName</code> 集群组名
 * <li><code>filePath</code> 文件地址
 * <li>{@link #getFileId()} 集群文件主键
 * </ul>
 *
 * <p>2015年10月23日 下午4:01:21
 * <p>Copyright (c) 2015 数联中国
 *
 * @author zhangyc
 */
public class UploadResult implements Serializable {

    private static final long serialVersionUID = -5722009254193060990L;
    /**
     * 是否上传成功
     */
    private boolean isSuccess;
    /**
     * 集群组名
     */
    private String groupName;
    /**
     * 文件地址
     */
    private String filePath;

    public UploadResult(boolean isSuccess, String groupName, String filePath) {
        this.isSuccess = isSuccess;
        this.groupName = groupName;
        this.filePath = filePath;
    }

    private static Pattern pattern = Pattern.compile("/([a-z0-9]*)/(.*)");

    public static UploadResult parseFromFileId(String fileId) {
        Matcher matcher = pattern.matcher(fileId);
        return matcher.matches() ? new UploadResult(true, matcher.group(1), matcher.group(2)) : null;
    }

    /**
     * 集群文件主键 eg：/group1/M00/00/00/c-dlOFYkquqALNdeAAOiGWvXGqA783.jpg
     *
     * @return String fileId
     */
    public String getFileId() {
        return isSuccess ? "/" + groupName + "/" + filePath : null;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public String getGroupName() {
        return groupName;
    }

    public String getFilePath() {
        return filePath;
    }

    @Override
    public String toString() {
        return "UploadResult{" +
                "isSuccess=" + isSuccess +
                ", groupName='" + groupName + '\'' +
                ", filePath='" + filePath + '\'' +
                '}';
    }
}
